package com.wl.shixun3.service;

import com.wl.shixun3.dao.UserDAO;
import com.wl.shixun3.entity.User;
import java.sql.SQLException;

public class UserService {
    private UserDAO userDAO;

    public UserService() {
        this.userDAO = new UserDAO();
    }

    // 用户注册
    public boolean registerUser(User user) {
        try {
            // 检查用户名是否已存在
            if (userDAO.checkIfUserExists(user.getUsername())) {
                return false;
            }
            // 插入新用户
            return userDAO.insertUser(user);
        } catch (SQLException e) {
            throw new RuntimeException("注册用户失败", e);
        }
    }

    // 用户登录验证
    public User login(String username, String password) {
        User user = userDAO.selectUser(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    // 检查用户名是否存在
    public boolean checkUsernameExists(String username) {
        return userDAO.checkIfUserExists(username);
    }

    // 根据用户名获取用户
    public User getUserByUsername(String username) {
        return userDAO.selectUser(username);
    }
    
    // 更新用户密码
    public boolean updatePassword(String username, String newPassword) {
        return userDAO.updatePassword(username, newPassword);
    }
    
    // 验证旧密码并更新新密码（供已登录用户使用）
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        User user = userDAO.selectUser(username);
        if (user != null && user.getPassword().equals(oldPassword)) {
            return userDAO.updatePassword(username, newPassword);
        }
        return false;
    }
}

